<?php

	require_once('../includes/config.php');
	require_once('../includes/functions.php');
	
	// Retrieve base HTML
	$pageStr = buildStandardPage('Edit User Profile','Edit User Profile');
	
	$content = '';
	
	if(isMobile()){
		$content .= 'Detected Mobile!';
	}
	else{
		if(true == isLoggedIn()){
			$userDescriptionArray = getUserAttributes();
			
			if(false == isset($_POST['submit'])){
				$id = getID();
				
				// get the user's info
				$query = buildSelectStatement('user', array('id' => $id));
				$result = executeSQL($query, 'Failed to retrieve the user\'s info.');
				$result = mysql_fetch_assoc($result);
			  
				$pageStr = buildStandardPage('Edit User','Edit User');

				$formName = 'validateEditForm';
				if(true == isBankManager()){
					$formName = 'validateEditFormManager';
				}
				
				// Build the form that allows the user to edit information
				$content .= '<form name=editForm method=post action=' 
					 . $_SERVER['PHP_SELF'] . ' onSubmit="return '.$formName.'(editForm)" >'
					 .' <input type=hidden name=id value=\''. $id . '\'>'
					 .' <input type=hidden name=salt value="'. $result['salt'] . '" >'
					 .'<table border=1 cellpadding=2 width=650>';

				// Populate the form
				foreach($result as $heading => $description){
					switch ($heading){
						case 'passwordhash': // Bank Managers cannot change passwords, unless it's theirs
							if(false == isBankManager() || ($_SESSION[$SELECTED_USER_ID] == $_SESSION['id']) ){ 
								$content .= '<tr><td>Password </td><td><input type=password value=\'\' name='. $heading . ' ></td></tr>';
							}
							break;
						case 'question': // Bank Managers cannot change security question, unless it's theirs
							if(false == isBankManager() || ($_SESSION[$SELECTED_USER_ID] == $_SESSION['id']) ){ 
								$content .= '<tr><td>' . $userDescriptionArray[$heading] . '</td><td><input type=text value=\'' . $description
								. '\' name='. $heading . ' ></td></tr>';  
							}

							break;
						case 'answerhash': // Bank Managers cannot change security question answers, unless it's theirs
							if(false == isBankManager() || ($_SESSION[$SELECTED_USER_ID] == $_SESSION['id']) ){
								$content .= '<tr><td>' . $userDescriptionArray[$heading] . '</td><td><input type=text value=\'' 
										 . '\' name='. $heading . ' ></td></tr>';  
							}
							break;
						case 'state':
							$content .= '</td><td>'. getStatesAsOptions();
							break;
						case 'accountNumber':
							if(2 == $result['roleid']){ // Only customers have accounts, so we'll only display accounts #s for customers
							$content .= '<tr><td>' . $userDescriptionArray[$heading] . '</td><td><input type=text value=\'' 
									. $description. '\' name='. $heading .' DISABLED ></td></tr>';
							}
							break;
						case 'roleid':
							if(false == isCustomer()){ // Customers cannot change user roles			
								$content .=  getUserRolesAsOptions($description);
							}
							break;
						case 'active':
							if(false == isCustomer()){ // Customers cannot make themselves active			
								$content .= getActiveOptions($description);
							}
							break;
						case 'salt':
						case 'id':
							break;
						default:
							$content .= '<tr><td>' . $userDescriptionArray[$heading] 
									. '</td><td><input type=text value=\'' 
									. $description . '\' name='. $heading 
							        . ' ></td></tr>';  
									//.((false == isAdmin()) || (true == isAdmin() && ($_SESSION[$SELECTED_USER_ID] == $_SESSION['id'])) ? ' ></td></tr>' : ' DISABLED ></td></tr>');  
					}
				}
				
				// Note - the user's salt is a hidden type that we'll pass through the POST 
				// so we don't have to query the DB for the salt after our POST
				
				if(true == isCustomer()){
					$content .= '</table><input type=hidden name=salt value= ' . $result['salt'] . ' ><input type=submit name=submit value=Update >'
					.'<input type=button name=cancel value=Cancel onclick="window.location=\'' 
					. $ACCOUNTS_URL . '\'" ></form>';					
				}
				else{
					$content .= '</table><input type=hidden name=salt value= ' . $result['salt'] . ' ><input type=submit name=submit value=Update >'
					.'<input type=button name=cancel value=Cancel onclick="window.location=\'' 
					. $USERS_URL . '\'" ></form>';
				}
				
			}
			else{
				//var_dump( $_POST);
				$tempArray = cleanPost($_POST);

				// get the id of the user we're editing
				$id = $tempArray['id'];

				// Remove values from the (old) POST array that we will not put into the database
				unset($tempArray['submit']);
				unset($tempArray['id']);
				date_default_timezone_set('America/Chicago');
				$tempArray['dob'] = strftime("%Y-%m-%d", strtotime($_POST['dob']));
				
				// if the password was updated we need to create a new hash
				if(($tempArray['passwordhash'] != '')){
					// update the user's hash
					$tempArray['passwordhash'] = hash('sha256', $tempArray['passwordhash'] . $tempArray['salt']);
				}
				// otherwise we don't have to update the hash
				else{
					unset($tempArray['passwordhash']);
				}
				
				// if the security answer was updated we need to create a new hash
				if(($tempArray['answerhash'] != '')){
					// update the user's hash
					$tempArray['answerhash'] = hash('sha256', $tempArray['answerhash'] . $tempArray['salt']);
				}
				// otherwise we don't have to update the hash
				else{
					unset($tempArray['answerhash']);
				}
				
				$updateQuery = buildUpdateStatement('user', $tempArray, $id);
				$saltResult = executeSQL($updateQuery, 'Failed to update the user\'s information.');
				
				if(true == isCustomer()){
					header('Location: ' . $ACCOUNTS_URL);
				}
				else{
					header('Location: ' . $USERS_URL);
				}
			}
		}
		else{
			$content .= $MUST_BE_LOGGED_IN;
		}
	}

	$pageStr = str_Replace('<!--content-->', $content, $pageStr);
	
	/**
	 * Send the generated HTML to the client's browser
	 */
	echo $pageStr;
?>